package com.team.weigou.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.etsy.android.grid.StaggeredGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.team.weigou.R;
import com.team.weigou.adapter.AutoImagePageAdapter;
import com.team.weigou.adapter.HomePtrStaggerAdapter;
import com.team.weigou.auto.AutoScrollViewPager;
import com.team.weigou.bean.HomeADBean;
import com.team.weigou.bean.HomeADEntity;
import com.team.weigou.bean.HomeDataEntity;
import com.team.weigou.config.UrlConfig;
import com.team.weigou.ui.GoodsActivity;
import com.team.weigou.ui.SearchActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZJ on 2015/7/6 0006.
 */

public class HomeFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2<StaggeredGridView>, AdapterView.OnItemClickListener{
    private HttpUtils httpUtils = new HttpUtils();
    BitmapUtils bitmapUtils;
    private ArrayList<HomeDataEntity> homeDataEntities = new ArrayList<>();
    private ImageView search_img;
    private PullToRefreshStaggeredGridView prrsgv;
    private HomePtrStaggerAdapter adapter;

    private HttpHandler<String> proHandler, bannerHandler;
    private int page = 1;
    private boolean isClear;
    private ViewHolder vh;
    private StaggeredGridView staggeredGridView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBitmUtils();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_layout, null);
        search_img = (ImageView) view.findViewById(R.id.search_img);
        search_img.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                startActivity(intent);
            }
        });
        initHeadView();
        initView(view, inflater);
        initData();
        return view;
    }

    /**
     * 初始化BitmapUtils工具类
     * //
     */
    private void initBitmUtils() {
        bitmapUtils = new BitmapUtils(getActivity());
        bitmapUtils.configDefaultLoadFailedImage(R.mipmap.ic_empty);
        bitmapUtils.configDefaultLoadingImage(R.mipmap.ic_empty);
    }

    /**
     * 初始化headview
     */
    private void initHeadView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.title_autoad_layout, prrsgv, false);
        vh = new ViewHolder(view);
    }

    @Override
    public void onResume() {
        super.onResume();
        vh.autoScrollViewPager.startAutoScroll();

    }

    @Override
    public void onPause() {
        super.onPause();
        vh.autoScrollViewPager.stopAutoScroll();
    }

    private void initView(View view, LayoutInflater inflater) {
        // listview + adapter + 数据源
        prrsgv = (PullToRefreshStaggeredGridView) view.findViewById(R.id.home_Gridview);
        prrsgv.setMode(PullToRefreshBase.Mode.BOTH);
        prrsgv.setOnRefreshListener(this);
        prrsgv.setOnItemClickListener(this);
        staggeredGridView = prrsgv.getRefreshableView();
        adapter = new HomePtrStaggerAdapter(homeDataEntities, getActivity(), bitmapUtils);
        prrsgv.setRefreshing();
        prrsgv.getRefreshableView().addHeaderView(vh.itemView);
        prrsgv.setAdapter(adapter);
    }


    //GridView数据加载
    private void initData() {
        getDataFromServer(UrlConfig.HOME_URL, adapter, homeDataEntities, prrsgv, isClear);

        RequestParams paramsAd = getADRequestParams();
        bannerHandler = new HttpUtils().send(HttpRequest.HttpMethod.POST, UrlConfig.HOME_AD_URL, paramsAd, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                HomeADBean homeADBean = com.alibaba.fastjson.JSONObject.parseObject(responseInfo.result, HomeADBean.class);
                if (homeADBean != null && "获取成功".equals(homeADBean.getMsg())) {
                    vh.autoImagePageAdapter.notifyDataSetChanged(homeADBean.getData());
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    public void getDataFromServer(String url, final BaseAdapter adapter, final List<HomeDataEntity> list, final PullToRefreshBase pullToRefreshBase, final boolean isClear) {
        RequestParams params = getRequestParams();
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        try {
                            String json = responseInfo.result;
                            String msg = new JSONObject(json).optString("msg");
                            if ("获取成功".equals(msg)) {
                                JSONArray arr = new JSONObject(json).getJSONArray("data");
                                List<HomeDataEntity> homeDataEntities = JSON.parseArray(arr.toString(), HomeDataEntity.class);
                                list.addAll(homeDataEntities);
                                adapter.notifyDataSetChanged();
                                pullToRefreshBase.onRefreshComplete();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                    }
                }
        );
    }

    private RequestParams getRequestParams() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("pageSize", "20");
        params.addBodyParameter("pageNo", String.valueOf(page));
        return params;
    }

    private RequestParams getADRequestParams() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("type", "0");
        params.addBodyParameter("num", "5");
        return params;
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        page = 1;
        isClear = true;
        initData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        page = 1;
        isClear = false;
        initData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getActivity(), GoodsActivity.class);
        intent.putExtra("shopId", homeDataEntities.get(position).getShopId());
        intent.putExtra("name", homeDataEntities.get(position).getProduct().getName());
        intent.putExtra("price", homeDataEntities.get(position).getProduct().getPrice());
        intent.putExtra("value", homeDataEntities.get(position).getProduct().getValue());
        intent.putExtra("image", homeDataEntities.get(position).getProduct().getImage());
        intent.putExtra("backMoney", "0");
        startActivity(intent);
    }

    /**
     * headView
     * //
     */
    private class ViewHolder {
        private AutoScrollViewPager autoScrollViewPager;
        private AutoImagePageAdapter autoImagePageAdapter;
        private View itemView;
        private LinearLayout dotLayout;


        private List<HomeADEntity> imgUrls = new ArrayList<>();


        public ViewHolder(View itemView) {
            this.itemView = itemView;
            this.autoScrollViewPager = (AutoScrollViewPager) itemView.findViewById(R.id.auto_viewpger);
            dotLayout = (LinearLayout) itemView.findViewById(R.id.auto_dot_layout);
            autoImagePageAdapter = new AutoImagePageAdapter(imgUrls, getActivity(), dotLayout, bitmapUtils);
            autoScrollViewPager.setOnPageChangeListener(autoImagePageAdapter);
            autoScrollViewPager.setAdapter(autoImagePageAdapter);

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        proHandler.cancel();
    }

}
